import UIKit

public protocol CustomTagHandlerDelegate: AnyObject {
    func customTag(didTap tag: String, attributes: [String: String], content: String)
}

public typealias CustomViewBuilder = (_ attributes: [String: String], _ content: String) -> UIView?

public class CustomTagHandler {
    public weak var delegate: CustomTagHandlerDelegate?
    
    private var customViewBuilders: [String: [String: CustomViewBuilder]] = [:]
    
    public init() {}
    
    public func registerCustomHTMLNodeView(
        forTag tag: String,
        className: String,
        builder: @escaping CustomViewBuilder
    ) {
        if customViewBuilders[tag] == nil {
            customViewBuilders[tag] = [:]
        }
        customViewBuilders[tag]?[className] = builder
    }
    
    public func createCustomView(
        forTag tag: String,
        className: String?,
        attributes: [String: String],
        content: String
    ) -> UIView? {
        guard let className = className,
              let tagBuilders = customViewBuilders[tag],
              let builder = tagBuilders[className] else {
            return nil
        }
        
        let view = builder(attributes, content)
        
        // 添加点击手势
        if let view = view {
            let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
            view.isUserInteractionEnabled = true
            view.addGestureRecognizer(tapGesture)
            
            // 存储标签信息
            let tagInfo = TagInfo(tag: tag, attributes: attributes, content: content)
            objc_setAssociatedObject(tapGesture, &AssociatedKeys.tagInfo, tagInfo, .OBJC_ASSOCIATION_RETAIN)
        }
        
        return view
    }
    
    @objc private func handleTap(_ gesture: UITapGestureRecognizer) {
        guard let tagInfo = objc_getAssociatedObject(gesture, &AssociatedKeys.tagInfo) as? TagInfo else {
            return
        }
        
        delegate?.customTag(didTap: tagInfo.tag, attributes: tagInfo.attributes, content: tagInfo.content)
    }
}

public struct TagInfo {
    public let tag: String
    public let attributes: [String: String]
    public let content: String
    
    public init(tag: String, attributes: [String: String], content: String) {
        self.tag = tag
        self.attributes = attributes
        self.content = content
    }
}

private struct AssociatedKeys {
    static var tagInfo = "tagInfo"
}

// Add new parseTag method
public struct ParsedTagInfo {
    public let tag: String
    public let className: String?
    public let attributes: [String: String]
    public let content: String
}

extension CustomTagHandler {
    public func parseTag(from htmlString: String) -> ParsedTagInfo? {
        // 匹配开始标签、属性和内容
        let pattern = "<([a-zA-Z][a-zA-Z0-9]*)([^>]*)>([^<]*)"
        
        guard let regex = try? NSRegularExpression(pattern: pattern, options: []),
              let match = regex.firstMatch(in: htmlString, options: [], range: NSRange(htmlString.startIndex..., in: htmlString)) else {
            return nil
        }
        
        // 提取标签名
        guard let tagRange = Range(match.range(at: 1), in: htmlString) else { return nil }
        let tag = String(htmlString[tagRange])
        
        // 提取属性字符串
        guard let attributesRange = Range(match.range(at: 2), in: htmlString) else { return nil }
        let attributesString = String(htmlString[attributesRange])
        
        // 解析属性
        let attributes = parseAttributes(from: attributesString)
        
        // 提取内容
        let content: String
        if let contentRange = Range(match.range(at: 3), in: htmlString) {
            content = String(htmlString[contentRange])
        } else {
            content = ""
        }
        
        // 提取class属性
        let className = attributes["class"]
        
        return ParsedTagInfo(tag: tag, className: className, attributes: attributes, content: content)
    }
    
    private func parseAttributes(from attributesString: String) -> [String: String] {
        var attributes: [String: String] = [:]
        
        // 匹配属性名和值
        let pattern = #"([a-zA-Z-]+)="([^"]*)"#
        
        guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else {
            return attributes
        }
        
        let matches = regex.matches(in: attributesString, options: [], range: NSRange(attributesString.startIndex..., in: attributesString))
        
        for match in matches {
            guard let nameRange = Range(match.range(at: 1), in: attributesString),
                  let valueRange = Range(match.range(at: 2), in: attributesString) else {
                continue
            }
            
            let name = String(attributesString[nameRange])
            let value = String(attributesString[valueRange])
            attributes[name] = value
        }
        
        return attributes
    }
    
    public func createView(for tagInfo: ParsedTagInfo) -> UIView? {
        guard let className = tagInfo.className, let builder = customViewBuilders[tagInfo.tag]?[className] else {
            return nil
        }
        return builder(tagInfo.attributes, tagInfo.content)
    }
}
